package leetcode_1_200;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class LeeCode_130 {
    public static void main(String[] args) {
        solve(new char[][]{{'X','X','X','X'},{'X','O','O','X'},{'X','X','O','X'},{'X','O','X','X'}});
        solve(new char[][]{{'X'}});
    }
    private static void solve(char[][] board) {
        int m = board.length;
        int n = board[0].length;
        Set<String> free = new HashSet<>();
        for (int j = 0; j < n; j++) {
            if (board[0][j] == 'O'){
                dfs(0, j, free, m, n,board);
            }
            if (board[m - 1][j] == 'O'){
                dfs(m - 1, j, free, m, n, board);
            }
        }
        for (int i = 1; i < m - 1; i++) {
            if (board[i][0] == 'O'){
                dfs(i, 0, free, m, n, board);
            }
            if (board[i][n - 1] == 'O'){
                dfs(i, n - 1, free, m, n, board);
            }
        }
        for (int i = 1; i < m - 1; i++) {
            for (int j = 1; j < n - 1; j++) {
                if (!free.contains(i + "," + j)){
                    board[i][j] = 'X';
                }
            }
        }
        for (int i = 0; i < m; i++) {
            System.out.println(Arrays.toString(board[i]));
        }
    }
    private static void dfs(int x, int y, Set<String> free, int m, int n, char[][] board){
        if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] == 'X')
            return;
        String key = x + "," + y;
        if (free.contains(key))
            return;
        free.add(key);
        dfs(x + 1, y, free, m, n, board);
        dfs(x - 1, y, free, m, n, board);
        dfs(x, y + 1, free, m, n, board);
        dfs(x, y - 1, free, m, n, board);
    }
}
